package com.cg.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cg.Dto.InsertBarnDto;
import com.cg.Dto.SearchBarnDto;
import com.cg.Dto.UpdateBarnDto;
import com.cg.Dto.UpdateBarnStatus;
import com.cg.common.StringConstant;
import com.cg.entity.Barn;
import com.cg.entity.Farm;
import com.cg.mapper.BarnMapper;
import com.cg.result.PageVO;
import com.cg.result.R;
import com.cg.service.BarnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cg.service.FarmService;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhy
 * @since 2024-12-26
 */
@Service
public class BarnServiceImpl extends ServiceImpl<BarnMapper, Barn> implements BarnService {
    @Resource
    private FarmService farmService;
    @Override
    public R<Barn> searchList(SearchBarnDto searchBarnDto) {
        Page<Barn> page =new Page<> (searchBarnDto.getPageNumber (),searchBarnDto.getPageSize ());
        try {
            // 构造查询条件并进行非空检查
            LambdaQueryWrapper<Barn> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(searchBarnDto.getFarmName())) {
                wrapper.like(Barn::getFarmName, searchBarnDto.getFarmName());
            }
            if (StringUtils.isNotBlank(searchBarnDto.getBarnName())) {
                wrapper.like(Barn::getBarnName, searchBarnDto.getBarnName());
            }
            if (searchBarnDto.getStatus() != null) {
                wrapper.eq(Barn::getStatus, searchBarnDto.getStatus());
            }
            if(searchBarnDto.getFarmId ()!=null)
            {
                wrapper.eq (Barn::getFarmId,searchBarnDto.getFarmId ());
            }
            // 执行查询并返回结果
            Page<Barn> page1 = this.page ( page, wrapper );
            PageVO<Barn> pageVO =new PageVO<> ();
            BeanUtils.copyProperties (page1,pageVO);
            return R.Success(pageVO);
        } catch (Exception e) {
            e.printStackTrace(); // 或者记录日志
            return R.Failed("查询失败");
        }
    }
    @Override
    public R<Barn> insertBarn(InsertBarnDto insertBarnDto) {
        try {
            // 获取所有农场记录
            List<Farm> farmList = farmService.list ();
            // 检查并获取或创建农场
                       Farm farm = farmList.stream ()
                               .filter ( data -> data.getFarmName ().equals ( insertBarnDto.getFarmName () ) )
                               .findFirst ()
                               .orElseGet ( () -> {
                                   Farm newFarm = new Farm ();
                                   newFarm.setFarmName ( insertBarnDto.getFarmName () );
                                   farmService.save ( newFarm );
                                   return newFarm;
                               } );
                       // 检查同一农场下是否存在相同的圈舍名称
                       LambdaQueryWrapper<Barn> wrapper = new LambdaQueryWrapper<Barn> ()
                               .eq ( Barn::getFarmId, farm.getId () )
                               .eq ( Barn::getBarnName, insertBarnDto.getBarnName () );
                       if (this.count ( wrapper ) > 0) {
                           return R.Failed ( StringConstant.BARNNAMENOEXISTS );
                       }
                       // 创建新的 Barn 实体并复制属性
                       Barn barn = new Barn ();
                       BeanUtils.copyProperties ( insertBarnDto, barn );
                       barn.setFarmId (farm.getId ());
                       // 保存新的圈舍信息
                       save ( barn );
            // 返回成功结果
            return R.Success ( StringConstant.INSERTSUCCESS );
        } catch (Exception e) {
            // 处理异常情况，并返回失败的结果
            e.printStackTrace (); // 或者记录日志
            return R.Failed ( StringConstant.FAEMNAMENOEXIXTS );
        }
    }
    @Override
    public R<Barn> updateBarn(UpdateBarnDto updateBarnDto) {
            // 获取当前要更新的圈舍信息
            Barn existingBarn = this.getById ( updateBarnDto.getId () );
            if (existingBarn == null) {
                return R.Failed ( "圈舍不存在" );
            }
            // 检查同一农场下是否存在相同的圈舍名称，但不包括当前正在更新的圈舍
            LambdaQueryWrapper<Barn> checkWrapper = new LambdaQueryWrapper<Barn> ()
                    .eq ( Barn::getFarmId, existingBarn.getFarmId () )
                    .eq ( Barn::getBarnName, updateBarnDto.getBarnName () )
                    .ne ( Barn::getId, updateBarnDto.getId () );  // 排除当前正在更新的圈舍
            if (this.count ( checkWrapper ) > 0) {
                return R.Failed ( StringConstant.BARNNAMENOEXISTS );
            }
            // 如果圈舍名称没有变化，则不需要更新
            if (existingBarn.getBarnName ().equals ( updateBarnDto.getBarnName () )) {
                return R.Success ("不更新");
            }
            // 构造更新条件
            LambdaUpdateWrapper<Barn> updateWrapper = new LambdaUpdateWrapper<Barn> ()
                    .set ( Barn::getBarnName, updateBarnDto.getBarnName () )
                    .eq ( Barn::getId, updateBarnDto.getId () );
            // 执行更新操作
            boolean updated = this.update ( updateWrapper );
            if (updated) {
                return R.Success ( StringConstant.UPDATESUCCESS );
            } else {
                return R.Failed ( StringConstant.UPDATEFAILED );
            }
        }
    @Override
    public R<Barn> updateStatus(UpdateBarnStatus updateBarnStatus) {
        LambdaUpdateWrapper<Barn> wrapper =new LambdaUpdateWrapper<Barn> ()
                .set (Barn::getStatus,updateBarnStatus.getStatus ())
                .eq (Barn::getId,updateBarnStatus.getId ());
          Boolean update = this.update (wrapper);
          if (update)
          {
              return R.Success (StringConstant.UPDATESUCCESS);
          }
          return  R.Failed (StringConstant.UPDATEFAILED);
    }
}
